<?php
/**
 * 需求管理
 * author@cailiang
 * date@2019-6-4
 * power by  zheyangxue
 */

define('EmpireCMSAdmin', '1');
require("../class/connect.php");
require("../class/db_sql.php");
require("../class/functions.php");
require LoadLang("pub/fun.php");
require("../data/dbcache/class.php");
$link = db_connect();
$empire = new mysqlquery();
//验证用户
//var_dump($_COOKIE);die;
//$lur = is_login();
$logininid = $_COOKIE['qlnxwloginuserid'];
$loginin = $lur['qlnxwloginusername'];
$loginrnd = $lur['qlnxwloginrnd'];
$loginlevel = $lur['qlnxwloginlevel'];
$loginadminstyleid = $lur['qlnxwloginadminstyleid'];
//ehash
$ecms_hashur = hReturnEcmsHashStrAll();
//验证权限
CheckLevel($logininid, $loginin, $classid, "searchkey");
$status = $_GET['status'];
$method = $_GET['method'];
$id = $_GET['id'];
switch ($method) {
    case 'list';
        requireList($status, $id);
        break;
    case 'edit';
        requireEdit($status, $id);
        break;
    case 'delete';
        requireDelete($status, $id);
        break;
    case 'examine';
        requireExamine($status, $id);
        break;
}
/**
 * 需求列表
 */
function requireList($status, $id)
{
    $line=25;//每页显示条数
    $page_line=18;//每页显示链接数
    $page=(int)$_GET['page'];
    $page=RepPIntvar($page);
    $start=0;
    $empire = new mysqlquery();
    if (!is_numeric($status)) {
        printerror2('参数错误');
    }
    switch ($status) {
        case 0;
            //  执行者不能看到改组数据    $_COOKIE['qlnxwloginlevel']     1超级管理员  2审核人   3执行人
            if ($_COOKIE['qlnxwloginlevel'] == 3) {
                $condition = 'status >1';
            } else {
                $condition = 'status >-1';
            }
            $title='申请管理';
            break;

        case 1;
            //  执行者不能看到改组数据    $_COOKIE['qlnxwloginlevel']     1超级管理员  2审核人   3执行人
            if ($_COOKIE['qlnxwloginlevel'] == 3) {
                $condition = 'status =-1';
            } else {
                $condition = 'status =0';
            }
            $title='审核管理';
            break;
        case 2;
            $condition = 'status =1';
            $title='执行管理';
            break;

        case 3;
            $condition = 'status =2';
            $title='已执行';
            break;
    }
    if($_POST['keyword']){
        $condition.="project like '%{$_POST['keyword']}%'";
    }
    $sql = "select id,project,applier_name,start_time,functional_module,status,username from  phome_ecms_requirement  where {$condition}";
    $re = $empire->query($sql);
    $num=$empire->num('select count(*)as num from  phome_ecms_requirement');
//    $returnpage=page2($num,$line,$page_line,$start,$page,$condition);
    require('template/requirementList.php'); //导入模板文件
}

/**
 * 编辑需求
 */
function requireEdit($status, $id)
{
    $empire = new mysqlquery();
    $userid = $_COOKIE['qlnxwloginuserid'];
    if (isset($_SERVER["HTTP_X_REQUESTED_WITH"]) && strtolower($_SERVER["HTTP_X_REQUESTED_WITH"]) == "xmlhttprequest") {
        $postid = $_POST['id'];
        //表单验证
        $msg = validateData($_POST['info']);
        if ($msg) {
            echo json_encode(array('code' => 400, 'msg' => $msg));
            die;
        }
        $filterArray = filterData($_POST['info']);
        if ($postid) {
            //编辑
            $sql = "update phome_ecms_requirement set {$filterArray['updateStr']} where id=$postid";
            $re = $empire->query($sql);
        } else {
            //添加
            $sql = "insert into phome_ecms_requirement ({$filterArray['fields']}) values ({$filterArray['values']})";
            $re = $empire->query($sql);
        }
        if ($re) {
            echo json_encode(array('code' => 200, 'msg' => '操作成功'));
            die;
        }
        // ajax 请求的处理方式
    } else {
        //获取需求详情
            $id=$id?$id:0;
            $sql = "select * from phome_ecms_requirement where id={$id} limit 1";
            $re = $empire->query($sql);
            $info = $empire->fetch($re);

        $listArr=array();
            //获取用户列表
        $user_sql ="select userid,username,groupid from phome_enewsuser where groupid>1 and groupid<4";
        $user_re = $empire->query($user_sql);
        while ($list=$empire->fetch($user_re)){
            $listArr[]=$list;
        }
        foreach ($listArr as &$value){
            $value['record']=$empire->fetch($empire->query("select * from phome_ecms_requirement_record where userid={$value['userid']} and requirement_id={$id}"));
        }
        unset($value);
        require('template/requirementEdit.php'); //导入模板文件
    }
}

/**
 * 审核需求
 */
function requireExamine($status, $id)
{
    $empire = new mysqlquery();
    if (isset($_SERVER["HTTP_X_REQUESTED_WITH"]) && strtolower($_SERVER["HTTP_X_REQUESTED_WITH"]) == "xmlhttprequest") {
       $post=array(
           'requirement_id'=>$_POST['requirement_id'],'add_time'=>date('Y-m-d'),'remark'=>$_POST['remark'],'status'=>$_POST['status']
       );
        switch ($_POST['groupid']){
            case 2;$post['type']=1; $changeStatus=1; break;
            case 3;$post['type']=2; $changeStatus=2;break;
        }
        $filterArray = filterData($post);
        //添加审核记录
        $record_sql = "insert into phome_ecms_requirement_record ({$filterArray['fields']}) values ({$filterArray['values']})";
        $record_re = $empire->query($record_sql);
        //修改状态
        $status_sql="update phome_ecms_requirement set status={$changeStatus} where id={$_POST['requirement_id']}";
        $status_re=$empire->query($status_sql);
        if ($status_re&&$record_re) {
            echo json_encode(array('code' => 200, 'msg' => '操作成功'));
            die;
        }
    }
}

/**
 * 过滤拼接字符串
 */
function filterData($info)
{
    $fields = array_keys($info);
    if (!is_array($fields)) {
        return false;
    }
    $updateStr = '';
    foreach ($fields as $value) {
        $info[$value] = trim($info[$value]);//去空格
        $info[$value] = new_addslashes($info[$value]);
        $info[$value] = new_stripslashes($info[$value]);
        $info[$value] = new_html_special_chars($info[$value]);
        $info[$value] = new_html_entity_decode($info[$value]);
        $info[$value] = safe_replace($info[$value]);
        $info[$value] = '\'' . remove_xss($info[$value]) . '\'';
        $updateStr .= $value . '=' . $info[$value] . ',';
    }
    unset($value);
    $fieldStr = trim(join(',', $fields)) . ',userid,username';
    $valueStr = trim(join(',', array_values($info))) . ",'{$_COOKIE['qlnxwloginuserid']}','{$_COOKIE['qlnxwloginusername']}'";
    return array('fields' => $fieldStr, 'values' => $valueStr, 'updateStr' => $updateStr);
}

/**
 * 返回经addslashes处理过的字符串或数组
 * @param $string 需要处理的字符串或数组
 * @return mixed
 */
function new_addslashes($string)
{
    if (!is_array($string)) return addslashes($string);
    foreach ($string as $key => $val) $string[$key] = new_addslashes($val);
    return $string;
}

/**
 * 返回经stripslashes处理过的字符串或数组
 * @param $string 需要处理的字符串或数组
 * @return mixed
 */
function new_stripslashes($string)
{
    if (!is_array($string)) return stripslashes($string);
    foreach ($string as $key => $val) $string[$key] = new_stripslashes($val);
    return $string;
}

/**
 * 返回经htmlspecialchars处理过的字符串或数组
 * @param $obj 需要处理的字符串或数组
 * @return mixed
 */
function new_html_special_chars($string)
{
    $encoding = 'utf-8';
    if (strtolower(CHARSET) == 'gbk') $encoding = 'ISO-8859-15';
    if (!is_array($string)) return htmlspecialchars($string, ENT_QUOTES, $encoding);
    foreach ($string as $key => $val) $string[$key] = new_html_special_chars($val);
    return $string;
}

function new_html_entity_decode($string)
{
    $encoding = 'utf-8';
    if (strtolower(CHARSET) == 'gbk') $encoding = 'ISO-8859-15';
    return html_entity_decode($string, ENT_QUOTES, $encoding);
}

function new_htmlentities($string)
{
    $encoding = 'utf-8';
    if (strtolower(CHARSET) == 'gbk') $encoding = 'ISO-8859-15';
    return htmlentities($string, ENT_QUOTES, $encoding);
}

/**
 * 安全过滤函数
 *
 * @param $string
 * @return string
 */
function safe_replace($string)
{
    $string = str_replace('%20', '', $string);
    $string = str_replace('%27', '', $string);
    $string = str_replace('%2527', '', $string);
    $string = str_replace('*', '', $string);
    $string = str_replace('"', '&quot;', $string);
    $string = str_replace("'", '', $string);
    $string = str_replace('"', '', $string);
    $string = str_replace(';', '', $string);
    $string = str_replace('<', '&lt;', $string);
    $string = str_replace('>', '&gt;', $string);
    $string = str_replace("{", '', $string);
    $string = str_replace('}', '', $string);
    $string = str_replace('\\', '', $string);
    return $string;
}

/**
 * xss过滤函数
 *
 * @param $string
 * @return string
 */
function remove_xss($string)
{
    $string = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S', '', $string);

    $parm1 = Array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');

    $parm2 = Array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');

    $parm = array_merge($parm1, $parm2);

    for ($i = 0; $i < sizeof($parm); $i++) {
        $pattern = '/';
        for ($j = 0; $j < strlen($parm[$i]); $j++) {
            if ($j > 0) {
                $pattern .= '(';
                $pattern .= '(&#[x|X]0([9][a][b]);?)?';
                $pattern .= '|(&#0([9][10][13]);?)?';
                $pattern .= ')?';
            }
            $pattern .= $parm[$i][$j];
        }
        $pattern .= '/i';
        $string = preg_replace($pattern, ' ', $string);
    }
    return $string;
}

/**
 * 表单验证
 */
function validateData($info)
{
    if (!$info['project']) {
        return '请输入项目名称';
    }
    if (!$info['functional_module']) {
        return '请输入功能模块';
    }
    if (!$info['department']) {
        return '请输入需求部门';
    }
    if (!$info['applier_name']) {
        return '请输入申请个人';
    }
    if (!$info['start_time']) {
        return '请输入提出时间';
    }
    if (!$info['end_time']) {
        return '请输入期望完成时间';
    }
    if (!$info['emergency_level']) {
        return '请选择紧急程度';
    }
    if (!$info['change_type']) {
        return '请选择变更类型';
    }
    if (!$info['change_reason']) {
        return '请选择变更原因';
    }
    if (!$info['requirement_desc']) {
        return '请选择需求描述';
    }
    return false;
}